package org.folio.rest.impl;

import cn.hutool.core.util.StrUtil;
import io.vertx.core.AsyncResult;
import io.vertx.core.Context;
import io.vertx.core.Handler;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import org.folio.rest.impl.other.PartyLogSave;
import org.folio.rest.impl.other.PartyUtil;
import org.folio.rest.jaxrs.model.Errors;
import org.folio.rest.jaxrs.model.NotifyTemplate;
import org.folio.rest.jaxrs.model.NotifyTemplateCollection;
import org.folio.rest.jaxrs.model.NotifyTemplateGroup;
import org.folio.rest.jaxrs.resource.PartyNotifyTemplate;
import org.folio.rest.persist.PgUtil;
import org.folio.rest.persist.PostgresClient;
import org.folio.rest.persist.cql.CQLWrapper;
import org.folio.rest.tools.messages.Messages;
import org.folio.rest.tools.utils.ValidationHelper;

import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static io.vertx.core.Future.succeededFuture;

/**
 * @author lee
 * @Classname NotifyTemplate
 * @Description TODO
 * @Date 2020/6/18 16:40
 * @Created by lee
 */
public class NotifyTemplateImpl implements PartyNotifyTemplate  {
    private final Logger logger = LoggerFactory.getLogger("modparty");
    private final Messages messages = Messages.getInstance();
    private static final String NOTIFY_TABLE = "notify_template";


    @Override
    public void postPartyNotifyTemplate(String lang, NotifyTemplate entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        entity.setId(UUID.randomUUID().toString());
        PostgresClient pg = PgUtil.postgresClient(vertxContext, okapiHeaders);
                pg.save(NOTIFY_TABLE,entity,reply->{
            if (reply.succeeded())
            {
                asyncResultHandler.handle(succeededFuture(PostPartyNotifyTemplateResponse.respond201WithApplicationJson(entity,PostPartyNotifyTemplateResponse.headersFor201())));
                PartyLogSave.saveLog("新增名称为【" + entity.getName() + "】的模版 ",
                        2, entity.getMetadata(),entity.getOperator(), okapiHeaders, asyncResultHandler, pg);

            }else
            {
                ValidationHelper.handleError(reply.cause(), asyncResultHandler);
            }

        });
    }


    @Override
    public void getPartyNotifyTemplate(String query, int offset, int limit, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        CQLWrapper cql = null;
        if (!StrUtil.isBlankOrUndefined(query))
        {
            try {
                cql = PartyUtil.getCQL(query,limit,offset,NOTIFY_TABLE);
            }catch (Exception e)
            {
                asyncResultHandler.handle(succeededFuture(GetPartyNotifyTemplateResponse.respond400WithTextPlain(query)));
                return;
            }
        }
        PgUtil.postgresClient(vertxContext,okapiHeaders).
                get(NOTIFY_TABLE, NotifyTemplateGroup.class, new String[]{"*"}, cql,true,false,reply->{
                    if (reply.succeeded())
                    {
                        NotifyTemplateCollection notifytemplatecollection = new NotifyTemplateCollection();
                        List<NotifyTemplateGroup> notifyTemplateGroup = reply.result().getResults();
                        Integer totalRecords = reply.result().getResultInfo().getTotalRecords();
                        notifytemplatecollection.setNotifyTemplateGroup(notifyTemplateGroup);
                        notifytemplatecollection.setTotalRecords(totalRecords);
                        asyncResultHandler.handle(succeededFuture(GetPartyNotifyTemplateResponse.respond200WithApplicationJson(notifytemplatecollection)));
                    } else {
                        ValidationHelper.handleError(reply.cause(), asyncResultHandler);
                    }
                });
    }


    @Override
    public void getPartyNotifyTemplateById(String id, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        if (StrUtil.isBlankOrUndefined(id))
        {

            Errors valErr = ValidationHelper.createValidationErrorMessage("id", id,
                    "Can not request the id");
            asyncResultHandler.handle(succeededFuture(GetPartyNotifyTemplateByIdResponse.respond404WithTextPlain(valErr)));
            return;
        }
        PgUtil.postgresClient(vertxContext,okapiHeaders).getById(NOTIFY_TABLE,id,NotifyTemplate.class,reply->{
            if (reply.succeeded())
            {
                NotifyTemplate value = reply.result();
                asyncResultHandler.handle(succeededFuture(GetPartyNotifyTemplateByIdResponse.respond200WithApplicationJson(value)));
            }else
            {
                ValidationHelper.handleError(reply.cause(), asyncResultHandler);
            }
        });
    }


    @Override
    public void deletePartyNotifyTemplateById(String id, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        if (StrUtil.isBlankOrUndefined(id))
        {

            Errors valErr = ValidationHelper.createValidationErrorMessage("id", id,
                    "Can not delete the id");
            asyncResultHandler.handle(succeededFuture(DeletePartyNotifyTemplateByIdResponse.respond404WithTextPlain(valErr)));
            return;
        }
        PostgresClient pg = PgUtil.postgresClient(vertxContext, okapiHeaders);
                pg.delete(NOTIFY_TABLE,id,reply->{
            if (reply.succeeded())
            {
                asyncResultHandler.handle(succeededFuture(DeletePartyNotifyTemplateByIdResponse.respond204()));
                PartyLogSave.saveLog("删除编号为【" + id + "】的模版 ", 4,
                        null, okapiHeaders, asyncResultHandler, pg);
            }else
            {
                ValidationHelper.handleError(reply.cause(), asyncResultHandler);
            }
        });
    }

 
    @Override
    public void putPartyNotifyTemplateById(String id, String lang, NotifyTemplate entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {

        String noteId = entity.getId();
        if (noteId != null && !noteId.equals(id)) {
            logger.error("Trying to change note Id from " + id + " to " + noteId);
            Errors valErr = ValidationHelper.createValidationErrorMessage("id", noteId,
                    "Can not change the id");
            asyncResultHandler.handle(succeededFuture(PutPartyNotifyTemplateByIdResponse.respond404WithTextPlain(valErr)));
            return;
        }
        PostgresClient pg = PgUtil.postgresClient(vertxContext, okapiHeaders);
        pg.update(NOTIFY_TABLE, entity, id,
                        reply -> {
                            if (reply.succeeded()) {
                                if (reply.result().getUpdated() == 0) {
                                    asyncResultHandler.handle(succeededFuture(PutPartyNotifyTemplateByIdResponse
                                            .respond404WithTextPlain(id)));
                                } else { // all ok
                                    asyncResultHandler.handle(succeededFuture(
                                            PutPartyNotifyTemplateByIdResponse.respond204()));
                                    PartyLogSave.saveLog("删除编号为【" + id + "】的模版 ", 4,
                                            null, okapiHeaders, asyncResultHandler, pg);
                                }
                            } else {
                                ValidationHelper.handleError(reply.cause(), asyncResultHandler);
                            }
                        });
    }
}
